package com.andnnl.thread;

import com.andnnl.inti.Init;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * Created by chenss on 2024/6/7.
 */
public class ThreadLocalTest {
    static ThreadLocal<Integer> currentUser = ThreadLocal.withInitial(() -> null);

    public static void main(String[] args) {
        testSameThread();
        testMoreThread();

    }

    private static void testSameThread() {
        ThreadLocalTest test = new ThreadLocalTest();
        for (int i = 0; i < 3; i++) {
            test.testChange(i);
        }
    }
    private static void testMoreThread() {
        ThreadLocalTest test = new ThreadLocalTest();
        ExecutorService pool = Executors.newFixedThreadPool(2);
        for (int i = 0; i < 10; i++) {
            int finalI = i;
            pool.submit(() -> {
                test.testChange(finalI);
            });
        }
    }

    private void testChange(int userId) {
        String before = Thread.currentThread().getName() + " : " + currentUser.get();
        currentUser.set(userId);
        String after = Thread.currentThread().getName() + " : " + currentUser.get();
        System.out.println(before + " -> " + after);
    }
}
